<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="点检工单号" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="device_check_record" column-name="code" :is-edit="id" />
          <!-- <span v-else>{{ formData.code }}</span> -->
        </el-form-item>
        <el-form-item label="点检计划单号">
          <el-input v-if="!id" v-model="formData.planCode" placeholder="" disabled />
          <el-input v-else v-model="formData.planCode" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="点检设备" prop="bookId" class="clickChoose">
          <el-input v-if="!id" v-model="formData.bookName" placeholder="请选择" readonly />
          <!--          <el-select v-if="!formData.planCode" v-model="formData.bookId" clearable filterable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in equipmentList"-->
          <!--              :key="item.id"-->
          <!--              :label="item.deviceName"-->
          <!--              :value="item.id"-->
          <!--            />-->
          <!--          </el-select>-->
          <a v-if="!id" class="clickChoose_button" @click.prevent="chooseEquipments">
            <svg-icon icon-class="选择弹框" />
          </a>
          <el-input v-else v-model="formData.bookName" placeholder="点检设备" disabled />
        </el-form-item>
        <el-form-item label="设备位置">
          <el-input v-model="formData.location" disabled />
        </el-form-item>
        <el-form-item label="计划点检时间" prop="planTime">
          <el-date-picker
            v-model="formData.planTime"
            :disabled="formData.planCode"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="维保班组">
          <el-select v-model="formData.maintenanceId" clearable filterable placeholder="请选择" @change="loadPeople">
            <el-option
              v-for="item in teamList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <!-- <el-input v-else v-model="formData.maintenanceName" placeholder="暂无" disabled /> -->
        </el-form-item>
        <el-form-item label="班次">
          <DictSelect :band-value.sync="formData.shiftCode" dict-type="shiftCode" />
        </el-form-item>
        <el-form-item label="点检模板" prop="templateName" class="clickChoose">
          <el-input v-if="!id" v-model="formData.templateName" placeholder="请选择" readonly />
          <a v-if="!id" class="clickChoose_button" @click.prevent="chooseTemplates">
            <svg-icon icon-class="选择弹框" />
          </a>
          <!--          <el-input-->
          <!--            v-if="!formData.planCode"-->
          <!--            v-model="formData.templateName"-->
          <!--            readonly-->
          <!--            placeholder="请选择"-->
          <!--            @click.native="chooseTemplates"-->
          <!--          />-->
          <el-input v-else v-model="formData.templateName" placeholder="点检模板" disabled />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="备注"
            disabled
          />
        </el-form-item>
        <el-divider />
        <el-form-item label="点检人员" prop="checkPersonId">
          <el-select v-model="formData.checkPersonId" clearable filterable placeholder="请选择" @change="searchTeam">
            <el-option
              v-for="item in peopleList"
              :key="item.userId"
              :label="item.realName"
              :value="item.userId"
            />
          </el-select>
          <!--          <el-input v-else v-model="formData.checkPersonName" placeholder="暂无" disabled />-->
        </el-form-item>
        <el-form-item label="点检完成时间" prop="completeTime">
          <el-date-picker
            v-model="formData.completeTime"

            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
      </el-form>
      <div ref="table_container" class="table_container draggableTable addRow_table">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          row-key="id"
          style="width: 99.9%"
          :cell-class-name="cellClassName"
          :row-class-name="rowClassName"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" class="expand_container">
                <el-form-item label="点检结果" class="expand_radio">
                  <el-radio v-model="props.row.result" :label="1"><svg-icon icon-class="勾" /></el-radio>
                  <el-radio v-model="props.row.result" :label="0"><svg-icon icon-class="叉" /></el-radio>
                </el-form-item>
                <el-form-item label="现场照片" class="expand_file file double">
                  <FileManageFull
                    :file-names="props.row.docName"
                    :file-real-names="props.row.docRealName"
                    :file-urls="props.row.docUrl"
                    :row-index="props.$index"
                    @fileName="setFileName"
                  />
                </el-form-item>
                <el-form-item label="点检记录" class="double">
                  <el-input v-model="props.row.description" type="textarea" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="备注" class="double">
                  <el-input
                    v-model="props.row.remark"
                    maxlength="200"
                    show-word-limit
                    type="textarea"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="序号" width="70">
            <template slot-scope="scope">
              <div v-if="!scope.row.isAdd">{{ scope.row.sort }}</div>
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="点检项目">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.name" style="margin:10px 0;" type="textarea" autosize readonly /> -->
              <DivTextarea :row-value="scope.row.name" />
            </template>
          </el-table-column>
          <el-table-column prop="content" label="点检内容">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.content" style="margin:10px 0;" type="textarea" autosize readonly /> -->
              <DivTextarea :row-value="scope.row.content" />
            </template>
          </el-table-column>
          <el-table-column prop="way" label="点检方式">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.way" style="margin:10px 0;" type="textarea" autosize readonly /> -->
              <DivTextarea :row-value="scope.row.way" />
            </template>
          </el-table-column>
          <el-table-column prop="time" label="时间 ( S )" width="80">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.time" style="margin:10px 0;" type="textarea" autosize readonly /> -->
              <DivTextarea :row-value="scope.row.time" />
            </template>
          </el-table-column>
          <el-table-column prop="criterion" label="判断标准">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.criterion" style="margin:10px 0;" type="textarea" autosize readonly /> -->
              <DivTextarea :row-value="scope.row.criterion" />
            </template>
          </el-table-column>
          <el-table-column
            label="附件"
            min-width="120"
          >
            <template slot-scope="scope">
              <FileManage
                :file-names.sync="scope.row.fileName"
                :file-real-names.sync="scope.row.fileRealName"
                :file-urls.sync="scope.row.fileUrl"
                :readonly="true"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button v-if="formData.status ==0||formData.status ==1" @click.stop="save">保存</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo } from '@/api/equipmentManage/equipmentCheck/checkRecord'
import { list } from '@/api/equipmentManage/equipmentCheck/checkTemplate'
import { list as getEquipmentList } from '@/api/equipmentManage/baseInfo/equipmentInfo'
import { list as maintenanceTeamList } from '@/api/equipmentManage/baseInfo/maintenanceTeam'
import { personnellist } from '@/api/equipmentManage/equipmentRepair/equipmentReportRepair'
// import chooseTemplate from '../checkTemplate/searchTemplate.vue'
// import chooseEquipment from '../../baseInfo/equipmentInfo/chooseEquiment.vue'
import moment from 'moment'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  data() {
    return {
      formData: {
        location: '',
        code: undefined,
        planCode: undefined,
        bookId: undefined,
        bookName: undefined,
        templateId: undefined,
        templateName: undefined,
        startTime: undefined,
        endTime: undefined,
        nextTime: undefined,
        taskMode: undefined,
        period: undefined,
        periodUnit: undefined,
        maintenanceId: undefined,
        checkPersonId: undefined,
        shiftCode: undefined,
        remark: undefined,
        planTime: undefined,
        completeTime: '',
        detailList: [],
        checkPersonName: '',
        maintenanceName: '',
        id: '',
        status: '',
        planId: ''
      },
      tableData: [],
      equipmentList: [],
      templateList: [],
      teamList: [],
      peopleList: [],
      num: 1,
      roleOptions: [],
      rules: {
        code: [
          { required: true, message: '点检工单号不能为空', trigger: 'blur' }
        ],
        bookId: [
          { required: true, message: '点检设备不能为空', trigger: 'change' }
        ],
        templateName: [
          { required: true, message: '点检模版不能为空', trigger: 'change' }
        ],
        planTime: [
          { required: true, message: '计划点检时间不能为空', trigger: 'change' }
        ],
        completeTime: [
          { required: true, message: '点检完成时间不能为空', trigger: 'change' }
        ],
        taskMode: [
          { required: true, message: '任务启动方式不能为空', trigger: 'change' }
        ],
        period: [
          { required: true, message: '点检周期不能为空', trigger: 'change' }
        ],
        periodUnit: [
          { required: true, message: '周期单位不能为空', trigger: 'change' }
        ],
        checkPersonId: [
          { required: true, message: '点检人员不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.loadTeam()
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })

      this.formData.completeTime = moment(new Date()).format('YYYY-MM-DD HH:mm')
    } else { // 有id就是编辑
      this.getInfo()
      this.formData.id = this.id
    }
  },
  mounted() {
    this.loadPeoples()
    this.getList()
  },
  methods: {
    cellClassName(data) {
      console.log(data)
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) { // 单数行
          return 'fixed one'
        } else { // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length - 1) {
        return 'addRow'
      }
    },
    removeRow(row) {
      this.tableData.splice(this.tableData.indexOf(row), 1)
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.tableData = res.data.detailList
        this.formData.status = res.data.status
        this.$nextTick(() => {
          if (!this.formData.completeTime) {
            this.formData.completeTime = ''
          }
          this.$nextTick(() => {
            this.$refs.form.clearValidate('completeTime')
          })
          if (!this.formData.checkPersonId) {
            this.formData.checkPersonId = this.$store.state.user.userId
          }
        })
      })
    },
    getList() {
      list({ status: 1 }).then(res => {
        this.templateList = res.data
      })
      getEquipmentList({ status: 1 }).then(res => {
        this.equipmentList = res.data
      })
    },
    setFileName(...data) {
      const cacheTableData = this.$deepClone(this.tableData)
      cacheTableData[data[3]].docName = data[0]
      cacheTableData[data[3]].docRealName = data[1]
      cacheTableData[data[3]].docUrl = data[2]
      this.tableData = cacheTableData
    },
    // 根据点检人员id查询维保班组
    searchTeam(e) {
      this.peopleList.forEach(item => {
        if (item.userId == e) {
          this.formData.maintenanceId = item.maintenanceId
        }
      })
    },
    // 加载维保班组数据
    loadTeam() {
      maintenanceTeamList({ status: 1 }).then(res => {
        this.teamList = res.data
      })
    },
    // 加载点检人员数据
    loadPeople() {
      this.formData.checkPersonId = ''
      personnellist({
        maintenanceId: this.formData.maintenanceId,
        status: 1,
        maintenanceStatus: 1
      }).then(res => {
        this.peopleList = res.data
      })
    },
    // 加载点检人员数据
    loadPeoples() {
      personnellist({
        maintenanceId: this.formData.maintenanceId,
        status: 1,
        maintenanceStatus: 1
      }).then(res => {
        this.peopleList = res.data
        if (!this.id) {
          this.peopleList.forEach(ele => {
            if (ele.userId == this.$store.state.user.uId) {
              this.formData.checkPersonId = ele.userId
              this.formData.checkPersonName = ele.realName
              this.formData.maintenanceId = ele.maintenanceId
              this.formData.maintenanceName = ele.maintenanceName
            }
          })
        }
      })
    },
    // // 选择点检模板
    // chooseTemplates() {
    //   this.$layer.iframe({// 弹框
    //     content: {
    //       content: chooseTemplate, // 传递的组件对象
    //       parent: this, // 当前的vue对象
    //       data: {
    //         defaultValue: { id: this.formData.templateId ? this.formData.templateId : '', name: this.formData.templateName ? this.formData.templateName : '' }
    //       }// props
    //     },
    //     area: ['1320px', '600px'],
    //     title: '选择点检模版', // 标题
    //     shadeClose: false // 点击遮罩是否关闭
    //   })
    // },
    // // 选择点检设备
    // chooseEquipments() {
    //   this.$layer.iframe({// 弹框
    //     content: {
    //       content: chooseEquipment, // 传递的组件对象
    //       parent: this, // 当前的vue对象
    //       data: {
    //         bookId: this.formData.bookId ? this.formData.bookId : ''
    //       }// props
    //     },
    //     area: ['1320px', '600px'],
    //     title: '选择点检设备', // 标题
    //     shadeClose: false // 点击遮罩是否关闭
    //   })
    // },
    // 提交
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // console.log(this.tableData.filter(item => !item.result).length)
          if (this.tableData.filter(item => !item.result && item.result != 0).length > 0) {
            this.$message.warning('点检项目中点检结果不能为空')
            return
          }
          this.formData.detailList = this.$deepClone(this.tableData)
          this.formData.detailList.forEach(ele => {
            delete ele.id
          })
          addOrUpdate({ ...this.formData, isSubmit: 1 }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getList() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 保存
    save() {
      // if (this.tableData.some(item => item.name) || this.tableData.length == 0) {
      //   this.$message.warning('请添加点检项目')
      //   return false
      // }
      let tag = true
      this.$refs['form'].validateField(['code', 'bookId', 'planTime', 'checkPersonId', 'templateName'], (valid) => {
        if (tag && valid) {
          tag = false
        }
      })
      if (tag) {
        this.formData.detailList = this.$deepClone(this.tableData)
        this.formData.detailList.forEach(ele => {
          delete ele.id
        })
        addOrUpdate({ ...this.formData, isSubmit: 0 }).then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.$layer.close(this.layerid) // 关闭弹框
          this.$parent.refresh2() // 调用父组件的刷新方法
        })
      }
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    // 获取点检模版数据
    showTemplate(data, name, id, remark) {
      data.forEach(ele => {
        ele['itemId'] = ele.id
      })
      this.tableData = data
      this.formData.templateId = id
      this.formData.templateName = name
      this.formData.remark = remark
      this.getList()
    },
    // 获取点检设备id
    showEquipment(data) {
      this.formData.bookId = data.id
      this.formData.bookName = data.code + '/' + data.name
      this.formData.location = data.location
      this.getList()
    }
    //
  }
}
</script>

<style lang="less" scoped>
.expand_radio{
  padding-top: 20px;
}
//一姐让注掉的
// /deep/ .el-textarea__inner{
//   border: none !important;
//   background: none;
//   overflow: hidden;
// }
/deep/ .accessory{
  color: #387bfc;
}
</style>
